package com.kt.uokos.yimo.service.impl;

import com.github.pagehelper.PageHelper;
import com.kt.uokos.yimo.dao.Collect;
import com.kt.uokos.yimo.example.CollectExample;
import com.kt.uokos.yimo.mapper.CollectMapper;
import com.kt.uokos.yimo.service.CollectService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class CollectServiceImpl implements CollectService {

    @Resource
    private CollectMapper collectMapper;


    @Override
    public List<Collect> queryAllCollect(Integer userId, Integer valueId, Integer page, Integer size, String sort, String order) {
        CollectExample collectExample = new CollectExample();
        CollectExample.Criteria criteria = collectExample.createCriteria();
        if (userId != null){
            criteria.andUserIdEqualTo(userId);
        }
        if (valueId != null){
            criteria.andValueIdEqualTo(valueId);
        }
        collectExample.setOrderByClause(sort+" "+order);
        PageHelper.startPage(page,size);
        return collectMapper.selectByExample(collectExample);
    }

    @Override
    public int countById(Integer userId, byte tybe, Integer pid) {
        CollectExample example = new CollectExample();
        CollectExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId).andTypeEqualTo((byte)0).andValueIdEqualTo(pid).andDeletedEqualTo(false);
        return (int)collectMapper.countByExample(example);
    }

    @Override
    public Collect queryByTypeAndValueId(Integer userId, Byte type, Integer valueId) {
        CollectExample example = new CollectExample();
        example.or().andUserIdEqualTo(userId).andTypeEqualTo(type).andValueIdEqualTo(valueId);
        return collectMapper.selectOneByExample(example);
    }

    @Override
    public void deleteById(Integer id) {
        collectMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int add(Collect collect) {
        collect.setAddTime(LocalDateTime.now());
        collect.setUpdateTime(LocalDateTime.now());
        return collectMapper.insert(collect);
    }

    @Override
    public List<Collect> queryByType(Integer userId, Byte type, Integer page, Integer limit, String sort, String order) {

        CollectExample example = new CollectExample();

        if (type!=null){
            example.or().andTypeEqualTo(type);
        }
        example.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        PageHelper.startPage(page,limit);

        return collectMapper.selectByExample(example);
    }
}
